﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Windows;
using eLearning.Controls;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;

namespace eLearning.DosenView
{
    public partial class ResourcesFormPage : PhoneApplicationPage
    {
        public string selectedFile { get; set; }

        private Resources resource;
        private bool firstLoaded;
        private delegate void UploadUrl(object value);

        public ResourcesFormPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(DataContextPage_Loaded);
        }

        private void DataContextPage_Loaded(object sender, RoutedEventArgs e)
        {

            if (firstLoaded)
            {
                if (PhoneApplicationService.Current.State.ContainsKey(Config.RESOURCES))
                {
                    resource = (Resources)PhoneApplicationService.Current.State[Config.RESOURCES];
                    if (resource.Id != null)
                    {
                        textBoxJudul.Text = resource.Judul;
                        textBoxLink.Text = resource.Link;
                        if (resource.DetMatkul.Id != null)
                            textPerkuliahan.Text = "Materi " + resource.DetMatkul.Matkul.Nama;
                        if (resource.DetMatkul.Creator == null)
                        {
                            textBlockMatkul.Visibility = Visibility.Collapsed;
                            matkulList.Visibility = Visibility.Collapsed;
                        }
                    }
                    else
                    {
                        if (resource.DetMatkul.Id == null)
                        {
                            textBlockMatkul.Visibility = Visibility.Visible;
                            matkulList.Visibility = Visibility.Visible;
                            textPerkuliahan.Text = "Materi Baru";
                            LoadPerkuliahan();
                        }
                        else
                        {
                            textBlockMatkul.Visibility = Visibility.Collapsed;
                            matkulList.Visibility = Visibility.Collapsed;
                        }
                        textBoxJudul.Text = "";
                        textBoxLink.Text = "";
                        if (resource.DetMatkul.Id != null)
                            textPerkuliahan.Text = "Materi " + resource.DetMatkul.Matkul.Nama;
                    }
                }
            }
        }

        private void LoadPerkuliahan()
        {
            DetailMatkul kuliah = new DetailMatkul();
            kuliah.Creator = (Dosen)SavedUser.Instance.User.ConvertUser();
            string json = JsonConvert.SerializeObject(kuliah);

            string url = Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.PERKULIAHAN_DOSEN_VIEW_KEY;

            string urlformat = string.Format("{0}&{1}", url, Guid.NewGuid().ToString());
            Uri uri = new Uri(urlformat, UriKind.Absolute);

            WebClient webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();
            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(listPerkuliahan_UploadStringCompleted);            
            webClient.UploadStringAsync(uri, "POST", json);
        }

        private void listPerkuliahan_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                DetailMatkulList list = JsonConvert.DeserializeObject<DetailMatkulList>(e.Result);
                matkulList.ItemsSource = list;
                if(resource.DetMatkul.Matkul != null)
                    matkulList.SelectedItem = resource.DetMatkul.Matkul;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void SaveResource(Resources data)
        {
            string json = null, url = null;


            if (data.Id == null)
            {
                url = Config.Instance.RESOURCES_SERVICE_URL() + Config.ADD_ACTION_KEY; //create
            }
            else
            {
                url = Config.Instance.RESOURCES_SERVICE_URL() + Config.UPDATE_ACTION_KEY; //update
            }
            json = JsonConvert.SerializeObject(data);


            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            client.UploadStringCompleted += new UploadStringCompletedEventHandler(saveChange_UploadStringCompleted);

            try
            {
                client.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void saveChange_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)
                    return;

                MessageBox.Show("Message : " + e.Result);

                if (e.Result.Contains("Success"))
                    NavigationService.GoBack();

            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void buttonSave_Click(object sender, System.EventArgs e)
        {
            if (matkulList.Visibility == Visibility.Visible)
                resource.DetMatkul = (DetailMatkul)matkulList.SelectedItem;
            resource.Judul = textBoxJudul.Text;
            resource.Link = textBoxLink.Text;

            SaveResource(resource);
        }

        private void buttonCancel_Click(object sender, System.EventArgs e)
        {
            NavigationService.GoBack();
        }

        private void buttonUpload_Click(object sender, RoutedEventArgs e)
        {
            Utility.GotoPage(this, "/Controls/StorageBrowser.xaml");
            StorageBrowser.CallerPage(this);
        }

        public void ReadFile(string fileName, Stream fileStream)
        {
            Dictionary<string[], object> data = new Dictionary<string[], object>()
                    {
                        {new string[]{"uploadedfile", fileName}, FileUtil.ReadToEnd(fileStream)}
                    };

            parameters = data;
            Upload(Config.Instance.UPLOAD_SERVICE_URL() + Config.UPLOAD_ACTION_KEY);
        }

        string uploadLink = "";
        string boundary = "----------" + DateTime.Now.Ticks.ToString();
        public Dictionary<string[], object> parameters;
        
        public void Upload(string url)
        {
            // Prepare web request...
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
            myRequest.Method = "POST";
            myRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);

            myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
        }

        private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            Stream postStream = request.EndGetRequestStream(asynchronousResult);

            FileUtil.writeMultipartObject(postStream, parameters, boundary);
            postStream.Close();

            request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
        }

        private void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);

            Stream streamResponse = response.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8);

            uploadLink = streamRead.ReadToEnd();
            this.Dispatcher.BeginInvoke(() =>
            {
                textBoxLink.Text = uploadLink;
            });

            streamResponse.Close();
            response.Close();
        }

        private void buttonUploaded_Click(object sender, RoutedEventArgs e)
        {
            Utility.GotoPage(this, "/Controls/UploadedBrowser.xaml");
            UploadedBrowser.CallerPage(this);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
            {
                firstLoaded = false;
                textBoxLink.Text = selectedFile == null || string.IsNullOrEmpty(selectedFile) ? textBoxLink.Text : selectedFile;
            }
            else
            {
                firstLoaded = true;
            }
        }
    }
}